package edu.biwu.dao.impl;

import edu.biwu.dao.ProductDao;
import edu.biwu.po.Product;
import lombok.Setter;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;
@Setter
@Repository
public class ProductDaoImpl implements ProductDao {
    //通过setter方法在spring中注入QueryRunner对象
    @Autowired
    private QueryRunner queryRunner;

//   例如: public QueryRunner getQueryRunner() {
//        return queryRunner;
//    }

    @Override
    public List<Product> findAll() {
        try {
            return queryRunner.query("SELECT * FROM spring.product",new BeanListHandler<Product>(Product.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateProduct(Product product) {
        try {
            queryRunner.update("UPDATE spring.product SET pname=?,price=?,category=? WHERE pid=?", product.getPname(),
                    product.getPrice(), product.getCategory(), product.getPid());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
